  <template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="日期" prop="date">
        <el-date-picker clearable
                        v-model="queryParams.date"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="课程内容" prop="courseContent">
        <el-input
          v-model="queryParams.courseContent"
          placeholder="课程内容"
          clearable
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable>
          <el-option
            v-for="dict in dict.type.ya_task_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否合格" prop="qualified">
        <el-select v-model="queryParams.qualified" placeholder="请选择是否合格" clearable>
          <el-option
            v-for="dict in dict.type.ya_task_qualified"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="daily_tasksList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="日期" align="center" prop="date" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="阶段" align="center" prop="stage"/>
      <el-table-column label="课程内容" align="center" prop="courseContent">
      </el-table-column>
      <el-table-column label="任务状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ya_task_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="是否合格" align="center" prop="qualified">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ya_task_qualified" :value="scope.row.qualified"/>
        </template>
      </el-table-column>
      <el-table-column label="总结图片" align="center" prop="summaryPicUrl" >
        <template slot-scope="scope">
          <el-image v-if="scope.row.summaryPicUrl"
                    style="width: 50px; height: 50px"
                    :src="`${baseUrl}${scope.row.summaryPicUrl}`"
                    :preview-src-list="preList(baseUrl+scope.row.summaryPicUrl)">
          </el-image>
          <span v-else>未上传</span>
        </template>
      </el-table-column>
      <el-table-column label="难点反馈" align="center" prop="difficultyFeedback" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status < 4"
                     size="mini"
                     type="text"
                     icon="el-icon-check"
                     @click="handleDailyTask(scope.row)"
                     v-hasPermi="['teaching:daily_tasks:edit']"
          >{{scope.row.summaryPicUrl?'修改':'提交'}}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改每日任务对话框 -->
    <el-dialog :title="title" fullscreen :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="每日总结" name="1">

            <el-form-item label="总结图片" prop="summaryPicUrl">
              <file-upload v-model="form.summaryPicUrl"  :fileType="fileType" file-size="2048"/>
            </el-form-item>
            <el-form-item label="难点反馈" prop="difficultyFeedback">
              <el-input v-model="form.difficultyFeedback" type="textarea" placeholder="请输入内容" />
            </el-form-item>

          </el-tab-pane>
          <el-tab-pane label="高频面试题练习" name="2">
            <el-form-item label="类型" prop="interviewType">
              <el-radio-group v-model="interviewType">
                <el-radio :label="1">推荐题目练习</el-radio>
                <!--<el-radio :label="2">自选面试题</el-radio>-->
              </el-radio-group>
            </el-form-item>
            <el-card class="box-card" v-for="(interview,index) in interviewList">
              <el-form-item :label="'题目'+(index+1)" >
                {{interview.question}}
              </el-form-item>
              <el-form-item label="统计">
                粘贴率:{{interview.pasteRate}} 手写字数:{{interview.writeCount}} 粘贴字数:{{interview.pasteCount}} 删除字数:{{interview.deleteCount}} &nbsp;&nbsp; <el-button title="清空回答" type="danger" icon="el-icon-close" circle size="mini" @click="cleanInterview(interview)"></el-button>
              </el-form-item>
              <el-form-item label="答案">
                <el-input v-model="interview.answer" @input.native="summarizeInput(interview,$event)"  :id="'answer'+interview.interviewId" :ref="'answer'+interview.interviewId" type="textarea"  placeholder="答案" />
              </el-form-item>
              <!--v-loading="interview.score===-1"-->
              <el-form-item  >
<!--                得分:{{interview.score}}<br>
                建议:{{interview.advance}}-->
                {{interview.advance}}
              </el-form-item>
              <el-form-item prop="oper">
                <el-button @click="queryReferenceAnswer(interview.referenceAnswer)" type="success" plain >
                  参考答案
                </el-button>
                <el-button @click="autoCheckAnswer(interview)" type="primary" plain>
                  检查答案
                </el-button>
                <el-button @click="openMore=!openMore" type="warning" plain>
                  展开
                </el-button>
              </el-form-item>
              <el-form-item label="难点" v-show="openMore" prop="difficulty">
                <el-input v-model="interview.difficulty" type="textarea" onpaste="return false;" placeholder="对于参考答案哪里不理解" />
              </el-form-item>
              <el-form-item label="what" v-show="openMore" prop="what">
                <el-input v-model="interview.what" type="textarea" onpaste="return false;" placeholder="是什么" />
              </el-form-item>
              <el-form-item label="how" v-show="openMore" prop="how">
                <el-input v-model="interview.how" type="textarea" onpaste="return false;" placeholder="怎么用" />
              </el-form-item>
              <el-form-item label="why" v-show="openMore" prop="why">
                <el-input v-model="interview.why" type="textarea"  onpaste="return false;" placeholder="有什么用" />
              </el-form-item>
              <el-form-item label="if when" v-show="openMore" prop="ifThen">
                <el-input v-model="interview.ifThen" type="textarea" onpaste="return false;" placeholder="什么场景下用" />
              </el-form-item>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">提交任务</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-drawer
      title="参考答案"
      :visible.sync="drawer"
      :direction="direction"
      size="50%"
      :before-close="handleClose">
                       <span>
                       <mavon-editor v-model="referenceAnswer" :subfield="false" defaultOpen="preview" :editable="false" :toolbarsFlag="false" />
                       </span>
    </el-drawer>


    <el-drawer
      title="检查结果"
      :visible.sync="checkDrawer"
      :direction="direction"
      size="50%"
      :before-close="handleClose">
                       <span>
                         <el-progress v-if="percentage!==100" type="dashboard" :percentage="percentage" :color="colors"></el-progress>
                         <mavon-editor v-model="advance" :subfield="false" defaultOpen="preview" :editable="false" :toolbarsFlag="false" />
                       </span>
    </el-drawer>
  </div>
</template>

<script>
import { checkAnswerFromApi,queryDailyInterviewList,listDaily_tasks, getDaily_tasks, delDaily_tasks, addDailyTasks, updateDaily_tasks } from "@/api/teaching/daily_tasks";
export default {
  name: "Daily_tasks",
  dicts: ['ya_task_status', 'ya_task_qualified'],
  data() {
    return {
      openMore:false,
      checkDrawer:false,
      advance: "",
      score: 0,
      percentage:10,
      baseUrl: process.env.VUE_APP_BASE_API,
      fileType:["png","jpg","jpeg"],
      referenceAnswer: "",
      drawer: false,
      direction: 'rtl',
      //面试题列表
      interviewList:[{

      }],
      interviewType:1,
      activeName: '1',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 每日任务表格数据
      daily_tasksList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        date: null,
        classesId: null,
        studentId: null,
        status: null,
        qualified: null,
        summaryPicUrl: null,
        difficultyFeedback: null
      },
      // 表单参数
      form: {
        date:null,
        summaryPicUrl:null,
        difficultyFeedback:null
      },
      // 表单校验
      rules: {
        studentId: [
          { required: true, message: "学生ID不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "任务状态不能为空", trigger: "change" }
        ],
        summaryPicUrl: [
          { required: true, message: "总结图片必须上传", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    preList(url){
      return url.split(",");
    },
    //统计输入
    summarizeInput(interview,event){
      let oldValue = interview.oldAnswer;
      let deleteCount = interview.deleteCount;//累计删除字数
      let writeCount = interview.writeCount;//累计手写字数
      let pasteCount = interview.pasteCount;//累计粘贴字数
      let currentValue = event.target.value;
      interview.oldAnswer = event.target.value;
      if (event.inputType === 'insertText') {
        // 手写
        writeCount++;
      } else if (event.inputType === 'insertFromPaste') {
        //粘贴
        let pasteLength = currentValue.length-oldValue.length;
        pasteCount+=pasteLength;
        console.log('当前粘贴字数:'+pasteLength);
      }else if (event.inputType === 'deleteContentBackward') {
        //删除
        let deleteLength = oldValue.length-currentValue.length;
        deleteCount+=deleteLength;
        console.log('当前删除字数:'+deleteLength);
      }

      console.log('目前字数:'+currentValue.length + ' 累计粘贴字数:'+pasteCount + ' 累计手写字数:'+writeCount + ' 累计删除字数:'+deleteCount);

      // Calculate the handwriting rate
      let totalTypedCharacters = writeCount + pasteCount ;
      let handwritingRate = (writeCount / totalTypedCharacters) * 100;

      // Calculate the paste rate
      let pasteRate = (pasteCount / totalTypedCharacters) * 100;

      interview.pasteCount = pasteCount;
      interview.writeCount = writeCount;
      interview.deleteCount = deleteCount;
      interview.handwritingRate = handwritingRate.toFixed(2);
      interview.pasteRate = pasteRate.toFixed(2);
      // console.log('手写率: ' + interview.handwritingRate + '% 粘贴率: ' + interview.pasteRate + '%');
    },
    autoCheckAnswer(interview){
      if (interview.answer.length<10){
        interview.score = 0;
        interview.advance = "答案需要写详细一些，否则直接0分，连续这样班主任可能会找你哦";
        return;
      }
      if (interview.answer !== ''&& interview.answer!==null) {
        interview.score = -1;
        interview.advance = "";

        // 创建一个EventSource实例来连接服务器
        let url = `http://localhost/dev-api/ai/daily_tasks/stream/check_answer?question=${encodeURIComponent(interview.question)}&answer=${encodeURIComponent(interview.answer)}`;
        const eventSource = new EventSource(url);

        // 监听消息事件来接收数据
        eventSource.onmessage = function (event) {
          console.log('Received data:', event.data);
          // 这里可以根据需要处理接收到的数据
          interview.advance += event.data;
        };

        // 监听打开连接事件
        eventSource.onopen = function (event) {
          console.log('Connection to server opened.');
        };

        // 监听错误事件
        eventSource.onerror = function (event) {
          console.error('EventSource failed:', event);
          eventSource.close(); // 关闭连接
        };


       /* checkAnswerFromApi(interview).then(response=>{
          let i = 0;
          response.data.advance = response.data.appraise + "。" + response.data.advance;
          if (response.code === 200 && response.data.advance !== '') {
            interview.score = response.data.score;
            // interview.advance=response.data.advance;
            let task = setInterval(() => {
              try {
                interview.advance += response.data.advance[i++];
                if (i + 1 > response.data.advance.length) {
                  clearInterval(task);
                }
              } catch (e) {
                clearInterval(task);
              }
            }, 10);
          }
        })*/
      }
    },
    checkAnswer(interview){
      if (interview.answer !== '') {
        this.checkDrawer = true;
        this.percentage = 10;
        this.advance = "";
        let interval = setInterval(() => {
          if(this.percentage<100){
            this.percentage += Math.floor(Math.random()*(10));
          }
        }, 2000);
        checkAnswerFromApi(interview).then(response=>{
          let i = 0;
          if (response.code === 200 && response.data.advance!=='') {
            this.percentage = 100;
            this.advance+="得分:"+response.data.score+"\n";
            let task = setInterval(() => {
              this.advance += response.data.advance[i++];
              if (i + 1 > response.data.advance.length) {
                clearInterval(task);
                clearInterval(interval);
              }
            }, 1);
          }
        })
      }
    },
    queryReferenceAnswer(referenceAnswer){
      this.drawer = true;
      this.referenceAnswer = referenceAnswer;
    },
    handleClose(done) {
      done();
    },
    /** 查询每日任务列表 */
    getList() {
      this.loading = true;
      listDaily_tasks(this.queryParams).then(response => {
        this.daily_tasksList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        date: null,
        classesId: null,
        studentId: null,
        status: null,
        qualified: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        summaryPicUrl: null,
        difficultyFeedback: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加每日任务";
    },
    cleanInterview(interview){
      interview.score = 0;
      interview.advance = "";
      interview.appraise = "";
      interview.answer = "";
      interview.pasteCount = 0;
      interview.writeCount = 0;
      interview.deleteCount = 0;
      interview.handwritingRate = 0;
      interview.pasteRate = 0;
      interview.oldAnswer = 0;
    },
    /** 提交每日任务*/
    handleDailyTask(row){
      this.reset();
      this.form = row;
      if (!this.form.date) {
        this.$modal.msgError("每日任务日期不能为空");
        return;
      }
      queryDailyInterviewList(this.form.date,this.interviewType,this.form.classesId).then(response=>{
        //渲染之前初始化属性值(score,acvance),否则无法双向绑定
        response.forEach(data=>{
          this.cleanInterview(data);
        })
        this.interviewList = response;
        this.open = true;
        this.title = "提交每日任务";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDaily_tasks(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改每日任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          //手动校验答案
          let hasError=false;
          if(this.interviewList ){
            for (let i = 0; i < this.interviewList.length; i++) {
              let interview = this.interviewList[i];
              if (!interview.answer) {
                this.activeName = '2';
                this.$nextTick(()=>{
                  let ref = "answer"+interview.interviewId;
                  document.getElementById(ref).focus();
                })
                this.$modal.msgError("面试官这样问你，你还是认真说点哦！");
                return ;
              }

              if(interview.score<6){
                hasError=true;
              }
            }
          }

          if(hasError){
            this.$confirm('还有未及格题目, 是否继续?班主任要找你哦！', '提示', {
              confirmButtonText: '不管了,先提交',
              cancelButtonText: '再完善一下',
              type: 'warning'
            }).then(() => {
              this.submitTask();
            })
          }else {
            this.submitTask();
          }


        }else {
          this.activeName = '1';
          this.$modal.msgError("请上传今日课程总结");
        }
      });

    },
    submitTask(){
      //提交今日任务
      let dailyTask = this.form;
      dailyTask.studentInterviewRecordList = this.interviewList;
      addDailyTasks(dailyTask).then(response => {
        this.$modal.msgSuccess("提交每日任务成功");
        this.open = false;
        this.getList();
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除每日任务编号为"' + ids + '"的数据项？').then(function() {
        return delDaily_tasks(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('teaching/daily_tasks/export', {
        ...this.queryParams
      }, `daily_tasks_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
